<template>
  <!-- 顶部导航 -->
  <Header />

  <!-- 主内容区域 -->
  <div class="main">
    <div class="container">
      <!-- 桌面端显示 hero 和筛选 -->
      <div class="desktop-only">
        <div class="hero">
          <h1>记录思考，分享知识</h1>
          <p>一个专注于技术分享与生活感悟的个人博客</p>
        </div>
        <el-form inline class="articles-filter" @submit.prevent>
          <el-form-item>
            <el-input
              v-model="filters.search"
              placeholder="搜索文章标题"
              clearable
              @input="debouncedFetchArticles"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="filters.category"
              placeholder="选择分类"
              clearable
              @change="fetchArticles()"
            >
              <el-option
                v-for="cat in categories"
                :key="cat.id"
                :label="cat.name"
                :value="cat.slug"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="filters.tags"
              multiple
              placeholder="选择标签"
              @change="fetchArticles()"
            >
              <el-option
                v-for="tag in tags"
                :key="tag.id"
                :label="tag.name"
                :value="tag.slug"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <!-- 内容区域 -->
      <div class="content">
        <!-- 文章区域 -->
        <div class="articles">
          <h2 class="section-title">最新文章</h2>

          <!-- 错误提示 -->
          <el-alert
            v-if="error"
            type="error"
            :title="error"
            show-icon
            :closable="false"
            class="error-alert"
          />

          <!-- 加载中 -->
          <div v-if="loading" class="loading-placeholder">
            <div v-for="i in 3" :key="i" class="article-card skeleton">
              <div class="article-image skeleton-item"></div>
              <div class="article-content">
                <div class="article-meta">
                  <span class="category skeleton-item"></span>
                  <span class="date skeleton-item"></span>
                </div>
                <h3 class="article-title skeleton-item"></h3>
                <p class="article-excerpt skeleton-item"></p>
                <div class="article-footer">
                  <div class="tags">
                    <span class="skeleton-item tag"></span>
                  </div>
                  <div class="read-more skeleton-item"></div>
                </div>
              </div>
            </div>
          </div>

          <!-- 文章列表或空状态 -->
          <div v-else>
            <div v-if="posts.length" class="article-list">
              <div v-for="post in posts" :key="post.id" class="article-card">
                <div class="article-link" :aria-label="`在新窗口查看文章 ${post.title}`" @click="openArticleInNewTab(post.id)">
                  <img
                    v-if="post.cover"
                    :src="getCoverUrl(post.cover)"
                    class="article-image"
                    loading="lazy"
                    :alt="post.title"
                  />
                  <div
                    v-else
                    class="article-image"
                    :style="{ backgroundImage: `url(${defaultImages[post.id % defaultImages.length]})` }"
                  >
                    <el-icon class="image-placeholder-icon"><Picture /></el-icon>
                  </div>
                  <div class="article-content">
                    <div class="article-meta">
                      <span class="category">{{ post.category?.name || '未分类' }}</span>
                      <span class="date">{{ formatDate(post.published_at) }}</span>
                    </div>
                    <h3 class="article-title">{{ post.title }}</h3>
                    <p class="article-excerpt">{{ post.summary || '暂无简介' }}</p>
                    <div class="article-footer">
                      <div class="tags">
                        <el-tag v-for="tag in post.tags" :key="tag.id" size="small">{{ tag.name }}</el-tag>
                      </div>
                      <div class="read-more">阅读更多</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无文章" />
          </div>

          <!-- 分页 -->
          <div v-if="pagination.total > pagination.per_page" class="pagination">
            <el-pagination
              background
              layout="total, prev, pager, next"
              :total="pagination.total"
              :page-size="pagination.per_page"
              :current-page="pagination.current_page"
              @current-change="handlePageChange"
            />
          </div>
        </div>

        <!-- 侧边栏（仅桌面端显示） -->
        <div class="sidebar desktop-only">
          <div class="widget">
            <h3 class="widget-title">关于我</h3>
            <About />
          </div>
          <div class="widget">
            <h3 class="widget-title">热门分类</h3>
            <ul class="category-list">
              <li v-for="cat in categories" :key="cat.id" class="category-item">
                <a
                  href="#"
                  @click.prevent="filters.category = cat.slug; fetchArticles()"
                  :class="{ active: filters.category === cat.slug }"
                >
                  {{ cat.name }} <span class="count">({{ cat.count || 0 }})</span>
                </a>
              </li>
            </ul>
          </div>
          <div class="widget">
            <h3 class="widget-title">标签云</h3>
            <div class="tag-cloud">
              <el-tag
                v-for="tag in tags"
                :key="tag.id"
                :type="filters.tags.includes(tag.slug) ? 'primary' : 'info'"
                size="small"
                class="tag-item"
                @click="toggleTag(tag.slug)"
              >
                {{ tag.name }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <Footer />
</template>

<script setup>
import Header from '@/components/layout/Header.vue';
import About from '@/components/sidebar/About.vue';
import Footer from '@/components/layout/Footer.vue';

import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import frontApi from '@/api/front';
import { formatDate, debounce } from '@/utils/format';

// 默认图片
import defaultImage1 from '@/assets/images/defaults/1.jpg';
import defaultImage2 from '@/assets/images/defaults/2.jpg';
import defaultImage3 from '@/assets/images/defaults/3.jpg';
const defaultImages = [defaultImage1, defaultImage2, defaultImage3];

const router = useRouter();


// 文章相关状态
const filters = ref({
  search: '',
  category: '',
  tags: [],
});
const error = ref('');
const loading = ref(true);
const posts = ref([]);
const pagination = ref({
  current_page: 1,
  per_page: 5,
  total: 0,
  last_page: 1,
});
const categories = ref([]);
const tags = ref([]);

// 防抖获取文章
const debouncedFetchArticles = debounce(() => fetchArticles(), 300);

// 获取文章列表
const fetchArticles = async (page = 1) => {
  loading.value = true;
  error.value = '';
  try {
    const params = {
      page,
      per_page: pagination.value.per_page,
      category: filters.value.category || undefined,
      tags: filters.value.tags.length ? filters.value.tags.join(',') : undefined,
      search: filters.value.search || undefined,
    };


    const res = await frontApi.getAllArticles(params);
    console.log(res);
    posts.value = res.data;

    pagination.value = res.meta;
  } catch (err) {
    error.value = '获取文章失败，请稍后重试';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

// 获取分类和标签
const fetchMeta = async () => {
  try {
    const [catRes, tagRes] = await Promise.all([
      frontApi.getLatestCategories(),
      frontApi.getLatestTags(),
    ]);
    console.log(tagRes.data);
    categories.value = catRes.data;
    tags.value = tagRes.data;
  } catch (err) {
    ElMessage.error('获取分类或标签失败');
  }
};

// 在新窗口打开文章
const openArticleInNewTab = (id) => {
  const routeUrl = router.resolve({ path: `/post/${id}` }).href;
  window.open(routeUrl, '_blank');
};

// 切换标签
const toggleTag = (slug) => {
  const index = filters.value.tags.indexOf(slug);
  if (index === -1) {
    filters.value.tags.push(slug);
  } else {
    filters.value.tags.splice(index, 1);
  }
  fetchArticles();
};

// 页码变化
const handlePageChange = async (page) => {
  await fetchArticles(page); // 等待数据加载完成
  window.scrollTo({ top: 0, behavior: 'smooth' }); // 滚动到顶部
};

const getCoverUrl = (path) => {
  if (!path) return ''
  if (/^https?:\/\//.test(path)) return path
  const base = import.meta.env.VITE_API_BASE_URL?.replace(/\/$/, '') || ''
  return path.startsWith('storage/')
    ? `${base}/${path}`
    : `${base}/storage/${path}`
}

// 初始化
onMounted(() => {
  fetchMeta();
  fetchArticles();
});

// 清理防抖
onUnmounted(() => {
  debouncedFetchArticles.cancel?.();
});
</script>

<style scoped lang="scss">
/* 容器 */
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

.nav-icon {
  display: none;
  cursor: pointer;
  font-size: 24px;
  color: #334155;
  transition: color 0.2s ease;
  &:hover {
    color: #2563eb;
  }
}

/* 主内容 */
.main {
  padding: 48px 0 40px 0;
  background: #fafbfc;
}

.hero {
  text-align: center;
  padding: 56px 0 40px 0;
  margin-bottom: 36px;
  background: none;
  h1 {
    font-size: 38px;
    font-weight: 700;
    margin-bottom: 14px;
    color: #222;
    line-height: 1.2;
  }
  p {
    font-size: 19px;
    color: #888;
    line-height: 1.5;
  }
}

.content {
  display: flex;
  gap: 32px;
}

.articles-filter {
  margin-bottom: 28px;
  .el-form {
    display: flex;
    gap: 14px;
    flex-wrap: wrap;
  }
  .el-form-item {
    margin-bottom: 0;
  }
}

.articles {
  flex: 1;
}

.section-title {
  font-size: 28px;
  font-weight: 600;
  color: #222;
  margin-bottom: 20px;
}

.error-alert {
  margin-bottom: 16px;
}

.loading-placeholder {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

.skeleton {
  .skeleton-item {
    background: #e2e8f0;
    border-radius: 6px;
    animation: skeleton-loading 1.2s ease-in-out infinite;
  }
  .article-image {
    width: 100%;
    height: 240px;
  }
  .category,
  .date,
  .tag,
  .read-more {
    display: inline-block;
    width: 80px;
    height: 20px;
  }
  .article-title {
    width: 85%;
    height: 28px;
  }
  .article-excerpt {
    width: 100%;
    height: 48px;
  }
}

@keyframes skeleton-loading {
  0% { background-color: #e2e8f0; }
  50% { background-color: #cbd5e1; }
  100% { background-color: #e2e8f0; }
}

.article-list {
  display: grid;
  grid-template-columns: 1fr; /* 单列布局 */
  gap: 24px;
}

.article-card {
  background: #fff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  min-height: 440px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
  }
}

.article-link {
  display: flex;
  flex-direction: column; /* 垂直布局：图片在上，内容在下 */
  text-decoration: none;
  color: inherit;
}

.article-image {
  width: 100%; /* 图片占满宽度 */
  height: 240px; /* 增加图片高度 */
  object-fit: cover;
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f1f5f9;
  .image-placeholder-icon {
    color: #94a3b8;
    font-size: 48px;
    opacity: 0.5;
  }
}

.article-content {
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px; /* 统一子元素间距 */
}

.article-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  color: #888;
}

.category {
  background: #e0f2fe;
  color: #2563eb;
  padding: 4px 12px;
  border-radius: 6px;
  font-weight: 500;
}

.article-title {
  font-size: 20px;
  font-weight: 600;
  color: #222;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.article-excerpt {
  color: #555;
  font-size: 15px;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

.article-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto; /* 确保footer在底部 */
}

.tags .el-tag {
  margin-right: 8px;
  border-radius: 6px;
  font-size: 13px;
  padding: 4px 10px;
}

.read-more {
  color: #2563eb;
  font-size: 14px;
  font-weight: 500;
  transition: color 0.2s ease;
  &:hover {
    color: #1d4ed8;
  }
}

.pagination {
  margin-top: 32px;
  text-align: center;
}

.sidebar {
  width: 320px;
  flex-shrink: 0;
}

.widget {
  background: #fff;
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 28px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.widget-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #1e293b;
}

.category-list {
  list-style: none;
  padding: 0;
  .category-item {
    margin-bottom: 12px;
    a {
      display: flex;
      justify-content: space-between;
      font-size: 15px;
      color: #475569;
      text-decoration: none;
      transition: color 0.2s ease;
      &:hover,
      &.active {
        color: #2563eb;
      }
      .count {
        color: #94a3b8;
      }
    }
  }
}

.tag-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  .tag-item {
    cursor: pointer;
    border-radius: 6px;
    padding: 6px 12px;
    font-size: 13px;
    transition: transform 0.2s ease, background-color 0.2s ease;
    &:hover {
      transform: scale(1.05);
      background-color: #e0f2fe;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header .container {
    position: relative;
  }
  .main {
    padding: 18px 0;
    background: #f4f6fb;
  }
  .desktop-only {
    display: none;
  }
  .content {
    display: block;
  }
  .article-list,
  .loading-placeholder {
    grid-template-columns: 1fr;
  }
  .article-card {
    min-height: 340px;
    border-radius: 12px;
  }
  .article-image {
    height: 160px;
  }
  .widget {
    border-radius: 12px;
    padding: 16px;
  }
}
</style>